#!/bin/bash
# myrpcclient 编译脚本(支持交叉编译)
# Optional Environment Variables: 
#        TOOLCHAIN_FILE 指定交叉编译的工具链文件
#        MACHINE 目标平台, such as x86_64-linux-gnu,默认使用当前系统平台
#        PREFIX 安装路径
#        PROJECT_FOLDER cmake 生成的工程文件(Makefile)文件夹
#        BUILD_TYPE 编译版本类型(DEBUG|RELEASE),默认 DEBUG
#        BUILD_TEST 为 ON 时编译测试和工具程序
#        CONAN_PROFILE conan profile for cross building
#        CONAN_OPTIONS 执行conan install定义额外的参数

if ! which conan 2>/dev/null 
then 
    echo conan NOT FOUND. && exit 255
fi
if  ! python --version 2>/dev/null | grep "Python 3." 
then
    echo Python 3 required. && exit 255
fi
sh_folder=$(cd "$(dirname $0)"; pwd -P)
folder_name=$(basename $sh_folder) 
# 定义编译的版本类型(debug|release)
build_type=Release
[[ "${BUILD_TYPE,,}" =~ debug|release ]] && build_type=${BUILD_TYPE,,}

echo build_type=$build_type

# 是否编译测试和工具程序
build_test=False
[[ "${BUILD_TEST^^}" =  ON ]] && build_test=True
[[ "${BUILD_TEST^^}" = OFF ]] && build_test=False

machine=$(g++ -dumpmachine)
gcc_version=$(g++ -dumpversion)

[ -n "$MACHINE" ] && machine=$MACHINE
[ -n "$GCC_VERSION" ] && gcc_version=$GCC_VERSION

toolchain=
[ -n "$TOOLCHAIN_FILE" ] && toolchain="-DCMAKE_TOOLCHAIN_FILE=$TOOLCHAIN_FILE"

conan_profile=
[ -n "$CONAN_PROFILE" ] && conan_profile="-pr:h $CONAN_PROFILE"

[ -n "$PREFIX" ] && install_prefix="$PREFIX"
[ -z "$PREFIX" ] && install_prefix=$sh_folder/release/myrpcclient_$machine
[ -e "$install_prefix" ] && rm -fr "$install_prefix"

[ -n "$PROJECT_FOLDER" ] && prj_folder="$PROJECT_FOLDER"
[ -z "$PROJECT_FOLDER" ] && prj_folder=$sh_folder/../$folder_name.gnu

[ -d $prj_folder ] && rm -fr $prj_folder
mkdir -p $prj_folder || exit

# conan 安装依赖库
if [ -n "$conan_profile" ]
then
    conan install "$sh_folder" \
        $conan_profile \
        -pr:b default \
        -s build_type=${build_type^} \
        -o build_test=$build_test \
        $CONAN_OPTIONS \
        -if $prj_folder \
        --build missing $CONAN_REMOTE_REPO || exit
else
    # MinGW编译时要通过CC,CXX指定编译器
    # 参见: https://blog.csdn.net/10km/article/details/123542518
    [[ "$(uname -s)" =~ (MINGW|MSYS|CYGWIN) ]] && export  CC=$(which gcc) && export CXX=$(which g++) \
        && CONAN_OPTIONS="$CONAN_OPTIONS -o boost:without_stacktrace=True"
    conan install "$sh_folder" \
        -s build_type=${build_type^} \
        -s compiler=gcc \
        -s compiler.version=${gcc_version:0:3} \
        -s compiler.libcxx=libstdc++11 \
        -o build_test=$build_test \
        $CONAN_OPTIONS \
        -if $prj_folder \
        --build missing $CONAN_REMOTE_REPO || exit
fi


pushd $prj_folder


conan build -pf $install_prefix $sh_folder || exit
conan package -pf $install_prefix $sh_folder || exit

popd

